package com.example.authclient.config;

import com.example.authclient.feign.IndexClient;
import com.example.util.model.Role;
import com.example.util.model.SecurityLogin;
import com.example.util.utils.DfUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

@Slf4j
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    private   static final  Logger logger= LoggerFactory.getLogger(MyUserDetailsService.class);
    @Autowired
    private IndexClient indexClient;

  /*  public IndexClient getIndexClient() {
        return indexClient;
    }

    public void setIndexClient(IndexClient indexClient) {
        this.indexClient = indexClient;
    }*/

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SecurityLogin user = indexClient.userInfoByLoginName(s);
        if(DfUtils.isNotBank(user) && DfUtils.isNotBank(user.getId())){
            List<Role> lr =indexClient.userRoles(user.getId());
            user.setLr(lr);
        }else{
                throw new UsernameNotFoundException("用户名："+ user + "不存在！");
        }
        logger.info("认证用户: "+user);

        Collection<SimpleGrantedAuthority> collection = new HashSet<SimpleGrantedAuthority>();
        Iterator<Role> iterator =  user.getLr().iterator();
        while (iterator.hasNext()){
            collection.add(new SimpleGrantedAuthority(iterator.next().getRoleCode()));
        }
            collection.add(new SimpleGrantedAuthority("admin"));
//        collection.add()

//        return new org.springframework.security.core.userdetails.User(s,user.getLoginPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
        User cUser = new User(s,user.getLoginPassword(),collection);

//        User cUser = new User(s, user.getLoginPassword(),
//                AuthorityUtils.commaSeparatedStringToAuthorityList("SA"));
        return cUser;
    }


}
